from flask import Blueprint, request
from flask_restful import Api, Resource

from webapp.config.api_utils import oper_log, check_auth
from webapp.models import Grade, VTeacher, Room
from webapp.service.board_service import BoardService
from webapp.tools import download_bord_excel

course_board_app = Blueprint('board', __name__, url_prefix='/api/board')
course_board_api = Api(course_board_app)


@course_board_api.resource("", "/grade/<int:gradeId>")
class BoardGradeApi(Resource):
    @oper_log('以班级为纬度的课程表', request)
    @check_auth('course:list', request)
    def get(self, gradeId):
       return BoardService.gradeBoard(gradeId)

@course_board_api.resource("/grade/exportExcel/<int:gradeId>")
class BoardGradeDownloadApi(Resource):
    @oper_log('导出班级表', request)
    @check_auth('course:list', request)
    def get(self, gradeId):
        grade = Grade.query.filter(Grade.classid == gradeId).first()
        excelData = BoardService.gradeBoard(grade.classid)
        return download_bord_excel(excelData, grade.classname)

@course_board_api.resource("", "/teacher/<int:teacherId>")
class BoardTeacherApi(Resource):
    @oper_log('以教师为纬度的课程表', request)
    @check_auth('course:list', request)
    def get(self, teacherId):
       return BoardService.teacherBoard(teacherId)


@course_board_api.resource("/teacher/exportExcel/<int:teacherId>")
class BoardTeacherDownloadApi(Resource):
    @oper_log('导出教师表', request)
    @check_auth('course:list', request)
    def get(self, teacherId):
        vteacher = VTeacher.query.filter(VTeacher.user_id == teacherId).first()
        excelData = BoardService.teacherBoard(vteacher.user_id)
        return download_bord_excel(excelData, vteacher.nick_name)

@course_board_api.resource("", "/room/<int:roomId>")
class BoardRoomApi(Resource):
    @oper_log('以教室为纬度的课程表', request)
    @check_auth('course:list', request)
    def get(self, roomId):
       return BoardService.roomBoard(roomId)


@course_board_api.resource("/room/exportExcel/<int:roomId>")
class BoardRoomDownloadApi(Resource):
    @oper_log('导出教室表', request)
    @check_auth('course:list', request)
    def get(self, roomId):
        room = Room.query.filter(Room.id == roomId).first()
        excelData = BoardService.roomBoard(roomId)
        return download_bord_excel(excelData, room.roomname)